package com.lin.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.lin.subject.commom.enums.IsDeletedFlagEnum;
import com.lin.subject.domain.convert.SubjectCategoryConverter;
import com.lin.subject.domain.entity.SubjectCategoryBO;
import com.lin.subject.domain.entity.SubjectLabelBO;
import com.lin.subject.domain.service.SubjectCategoryDomainService;
import com.lin.subject.domain.utils.CacheUtil;
import com.lin.subject.infra.basic.entity.SubjectCategory;
import com.lin.subject.infra.basic.entity.SubjectLabel;
import com.lin.subject.infra.basic.entity.SubjectMapping;
import com.lin.subject.infra.basic.mapper.SubjectCategoryDao;
import com.lin.subject.infra.basic.service.SubjectCategoryService;
import com.lin.subject.infra.basic.service.SubjectMappingService;
import com.lin.subject.infra.basic.service.impl.SubjectLabelServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Resource
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;
    @Autowired
    private SubjectCategoryDao subjectCategoryDao;
    @Autowired
    private SubjectLabelServiceImpl subjectLabelService;

    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Resource
    private CacheUtil cacheUtil;

    public void add(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(subjectCategory);
    }

    /**
     * 查询分类列表
     *
     * @param subjectCategoryBO
     */
    @Override
    public List<SubjectCategoryBO> queryPrimaryCategory(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }

        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        // 所有一级分类
        List<SubjectCategory> subjectCategories = subjectCategoryService.queryCategory(subjectCategory);
        List<Long> ids = subjectCategories.stream().map(SubjectCategory::getId).collect(Collectors.toList());
        List<SubjectCategoryBO> subjectCategoryBOS = SubjectCategoryConverter.INSTANCE.convertCategoryToBoList(subjectCategories);

        // 分类count的转换 这个count是当前分类的count，但是要计算到一级分类上

        List<SubjectMapping> typeCount = subjectMappingService.querySubjectCount();

        // 实际上这个就是标签的count
        List<Long> notInTypeListIds = typeCount.stream()
                .filter(type -> !ids.contains(type.getCategoryId()))
                .map(SubjectMapping::getCategoryId).collect(Collectors.toList());

        // 遍历去找他的父亲 直到找到一级分类
        List<SubjectMapping> fatherSubjectMapping = recursiveFindFather(ids, notInTypeListIds, typeCount);


        Map<Long, SubjectMapping> collect = fatherSubjectMapping.stream().collect(Collectors.toMap(SubjectMapping::getCategoryId, Function.identity()));
        List<SubjectCategoryBO> realCategoryBOs = subjectCategoryBOS.stream().map(item -> {
            SubjectMapping innerType = collect.get(item.getId());
            if (Objects.nonNull(innerType)) {
                item.setCount(innerType.getCount());
            } else {
                item.setCount(0);
            }
            return item;
        }).collect(Collectors.toList());

        return realCategoryBOs;
    }

    /**
     * 遍历去找他的父亲 直到找到一级分类
     *
     * @param ids
     * @param notInTypeOneList
     * @param typeCount
     * @return
     */
    private List<SubjectMapping> recursiveFindFather(List<Long> ids, List<Long> notInTypeOneList, List<SubjectMapping> typeCount) {
        if (notInTypeOneList.isEmpty()) return typeCount;


        List<SubjectMapping> innerTypeCount = new ArrayList<>();
        List<Long> innerIdList = new ArrayList<>();

        notInTypeOneList.forEach(item -> {
            // 找到当前的数据
            SubjectCategory fatherSubject = subjectCategoryService.queryById(item);
            // 判断当前数据是否是1级分类
            if (!ids.contains(fatherSubject.getParentId()))
                innerIdList.add(fatherSubject.getParentId());
            // 当innerTypeCount不为空的时候，实际上就是1级分类
            SubjectMapping presenceMapping = innerTypeCount.stream()
                    .filter(type -> type.getSubjectId().equals(fatherSubject.getId())).findFirst()
                    .orElse(null);
            int index = innerTypeCount.indexOf(presenceMapping);

            // 从typeCount 中 找到categoryId = item.id
            SubjectMapping findSubjectMapping = typeCount.stream()
                    .filter(type -> type.getCategoryId().equals(fatherSubject.getId())).findFirst()
                    .orElse(null);

            SubjectMapping subjectMapping = new SubjectMapping();
            subjectMapping.setSubjectId(fatherSubject.getId());
            subjectMapping.setCount(findSubjectMapping.getCount());
            subjectMapping.setCategoryId(fatherSubject.getParentId());

            if (Objects.nonNull(presenceMapping)) {
                presenceMapping.setCount(presenceMapping.getCount() + subjectMapping.getCount());
                innerTypeCount.add(presenceMapping);
                innerTypeCount.remove(index);
            } else {
                innerTypeCount.add(subjectMapping);
            }
        });

        if (!innerIdList.isEmpty()) {
            return this.recursiveFindFather(ids, innerIdList, innerTypeCount);
        }

        // 做一个聚合的操作
        Map<Long, Integer> collect = innerTypeCount.stream().collect(Collectors.groupingBy(SubjectMapping::getCategoryId, Collectors.summingInt(SubjectMapping::getCount)));
        List<SubjectMapping> subjectMappings = new ArrayList<>();
        for (Long key : collect.keySet()) {
            SubjectMapping subjectMapping = new SubjectMapping();
            subjectMapping.setCategoryId(key);
            subjectMapping.setCount(collect.get(key));
            subjectMappings.add(subjectMapping);
        }

        return subjectMappings;
    }

    /**
     * 查询分类及标签
     *
     * @param subjectCategoryBO
     * @return
     */
    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> boList = SubjectCategoryConverter.INSTANCE
                .convertBoToListCategory(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.boList:{}",
                    JSON.toJSONString(boList));
        }
        boList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });
        return boList;
    }

    /**
     * 更新分类
     *
     * @param subjectCategoryBO
     * @return
     */
    @Override
    public int update(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }

        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);

        return subjectCategoryService.update(subjectCategory);
    }

    @Override
    public int delete(SubjectCategoryBO subjectCategoryBO) {

        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());

        return subjectCategoryService.update(subjectCategory);
    }


    /**
     * 查询分类及分类对应的标签
     * 1、先查询所有的分类
     * 2、批量查询标签
     * 这里使用了多线程
     *
     * @param subjectCategoryBO
     * @return
     */
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        Long id = subjectCategoryBO.getId();
        String cacheKey = "categoryAndLabel." + id;

        List<SubjectCategoryBO> subjectCategoryBOS = cacheUtil.getResult(cacheKey,
                SubjectCategoryBO.class, (key) -> getSubjectCategoryBOS(id));
        return subjectCategoryBOS;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long id) {
        //查询当前大类下所有分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(id);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryCategoryAndLabel.subjectCategoryList:{}",
                    JSON.toJSONString(subjectCategoryList));
        }

        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConverter.INSTANCE.convertCategoryToBoList(subjectCategoryList);

        Map<Long, List<SubjectLabelBO>> map = new HashMap<>();

        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = categoryBOList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getThreeTypeBOList(category), labelThreadPool)
        ).collect(Collectors.toList());

        completableFutureList.forEach(future -> {
            try {
                Map<Long, List<SubjectLabelBO>> resultMap = future.get();
                if (Objects.nonNull(resultMap)) {
                    map.putAll(resultMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        categoryBOList.forEach(categoryBO -> {
            categoryBO.setLabelBOList(map.get(categoryBO.getId()));
        });
        return categoryBOList;
    }

    private Map<Long, List<SubjectLabelBO>> getThreeTypeBOList(SubjectCategoryBO category) {
        Map<Long, List<SubjectLabelBO>> labelMap = new HashMap<>();
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(category.getId());
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategories = subjectCategoryService.queryCategory(subjectCategory);
        if (CollectionUtils.isEmpty(subjectCategories)) {
            return null;
        }

        List<SubjectLabelBO> labelBOList = new LinkedList<>();

        subjectCategories.forEach(item -> {
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            subjectLabelBO.setId(item.getId());
            subjectLabelBO.setLabelName(item.getCategoryName());
            subjectLabelBO.setCategoryId(item.getId());
            subjectLabelBO.setSortNum(1);
            labelBOList.add(subjectLabelBO);
        });
        labelMap.put(category.getId(), labelBOList);
        return labelMap;
    }

    private Map<Long, List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO category) {
        Map<Long, List<SubjectLabelBO>> labelMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(category.getId());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(mappingList)) {
            return null;
        }
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> labelBOList = new LinkedList<>();
        labelList.forEach(label -> {
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            subjectLabelBO.setId(label.getId());
            subjectLabelBO.setLabelName(label.getLabelName());
            subjectLabelBO.setCategoryId(label.getCategoryId());
            subjectLabelBO.setSortNum(label.getSortNum());
            labelBOList.add(subjectLabelBO);
        });
        labelMap.put(category.getId(), labelBOList);
        return labelMap;
    }
}
